package org.simplextensions.registry.phaselisteners;

import java.util.Collection;

import org.simplextensions.registry.ConfigurableElem;
import org.simplextensions.registry.Extension;
import org.simplextensions.registry.ExtensionPoint;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.registry.IExtensionValidator;

public class ValidationPhaseListener extends APhaseListener implements IValidationPhaseListener {

	@Override
	public void processExtension(ExtensionEvent extensionEvent) {
		extensionEvent.doit = validateConfigurationElem(extensionEvent.getExtensionRegistry(), extensionEvent.getExtension());
	}

	@Override
	public void processExtensionPoint(ExtensionPointEvent extensionPointEvent) {
		extensionPointEvent.doit = validateConfigurationElem(extensionPointEvent.getExtensionRegistry(), extensionPointEvent
				.getExtensionPoint());
	}

	private boolean validateConfigurationElem(IExtensionRegistry extensionRegistry, ConfigurableElem elem) {
		boolean valid = elem.getId() != null;

		if (elem instanceof Extension) {
			Extension extension = (Extension) elem;
			valid &= extension.getPointId() != null;

			if (valid) {
				ExtensionPoint extensionPoint = extension.getExtensionPoint();
				if (extensionPoint != null) {
					Collection<IExtensionValidator> validators = extensionPoint.getVaidators();

					for (IExtensionValidator validator : validators) {
						valid &= validator.isValid(extension);
						if (!valid)
							break;
					}
				}
			}
		}

		return valid;
	}
}
